package com.salefinder.server.server.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.salefinder.server.server.vo.BaseVO;

public abstract class BaseDao {

	protected static SessionFactory sessionFactory = buildSessionFactory();

	
	private static SessionFactory buildSessionFactory() {
		return new Configuration().configure().buildSessionFactory();
	}
	

	protected SessionFactory getSessionFactory(){
		return sessionFactory;
	}
	
	protected void createOrUpdate(BaseVO vo){
		try{
		Session session = this.getSessionFactory().getCurrentSession();
		session.beginTransaction();
			
		session.saveOrUpdate(vo);		
		session.getTransaction().commit();
	
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	protected void delete(BaseVO vo){
		try{
		Session session = this.getSessionFactory().getCurrentSession();
		session.beginTransaction();
			
		session.delete(vo);		
		session.getTransaction().commit();
	
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	protected BaseVO load(Class c, int id){
		BaseVO vo = null;
		try{
		Session session = this.getSessionFactory().getCurrentSession();
		session.beginTransaction();
			
		vo = (BaseVO) session.load(c, id);		
		session.getTransaction().commit();
	
		}catch(HibernateException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
		return vo;
	}

	protected void create(BaseVO vo){
		try{
		Session session = this.getSessionFactory().getCurrentSession();
		session.beginTransaction();
			
		session.save(vo);		
		session.getTransaction().commit();
	
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
